package com.gitee.feizns.web.boot.decrypt;

import com.gitee.feizns.web.aspectj.decrypt.DecryptInterceptor;
import com.gitee.feizns.web.ex.MessageException;
import com.gitee.feizns.web.utils.RsaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author feizns
 * @since 2019/8/3 0003
 */
@ConditionalOnMissingBean(DecryptInterceptor.class)
@Configuration
@EnableConfigurationProperties(DecryptProperties.class)
public class DecryptAutoConfiguration {

    @Autowired
    private DecryptProperties properties;

    @Bean
    public DecryptInterceptor decryptInterceptor() {
        RsaUtils utils = RsaUtils.getInstance();
        return new DecryptInterceptor(original -> {
            String ret = utils.decrypt(original, utils.getPrivateKey(properties.getPrivateKey()));
            if ( ret == null )
                throw new DecryptionFailedException();
            return ret;
        });
    }

    /**
     * 解密失败
     */
    public static class DecryptionFailedException extends MessageException {

        public DecryptionFailedException() {
            super(null);
        }

    }

}
